package me.pppploi8.docgenerate;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Scanner;

public class Main{
    public static void main(String[] args) throws Exception {
        String[] files = new String[]{"../web/js/webmcs.js"};
        for(String filename : files){
            File file = new File(filename);
            System.out.println("正在处理[" + file + "]文件");
            handleFile(file);
        }
        System.out.println("所有文件已处理完毕！");
    }
    public static void handleFile(File file) throws Exception {
        Scanner sc = new Scanner(new FileInputStream(file));
        StringBuffer output = new StringBuffer();
        boolean flag = false;
        StringBuffer tmp = null;
        while(sc.hasNext()){
            String line = sc.nextLine();
            if (line.contains("/** webmcs **")){
                tmp = new StringBuffer();
                flag = true;
            }else if(line.contains("**/")){
                //紧接着取下一行的函数名称
                line = sc.nextLine();
                line = line.substring(0, line.indexOf("=")).trim();
                output.append("函数名称 [").append(line).append("]  \r\n");
                output.append(tmp).append("\r\n");
                output.append("---\r\n\r\n");
                flag = false;
            }else if(flag){
                line = replaceFirst(line, "* name", "函数介绍:");
                line = replaceFirst(line, "* param", "参数 -");
                line = replaceFirst(line, "* return", "返回值:");
                tmp.append(line.trim()).append("  \r\n");
            }
        }
        sc.close();
        FileOutputStream fos = new FileOutputStream("../" + file.getName() + "-API.md");
        fos.write(output.toString().getBytes("UTF-8"));
        fos.close();
    }
    public static String replaceFirst(String str, String oldStr, String newStr) {
        int i = str.indexOf(oldStr);
        if (i != -1) {
            return str.substring(0, i) + newStr + str.substring(i + oldStr.length());
        } else {
            return str;
        }
    }
}